package com.quikin.springjpa.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.quikin.common.util.IConstants;
import com.quikin.persistence.stdjpa.util.PersistenceConfigure;
import com.von.platform.impl.openjpa.std.EntityManagerContanier;

public class TransactionInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = Logger.getLogger(TransactionInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        try {
            EntityManager em = EntityManagerContanier.getInstance().getCurrentEntityManager(IConstants._PERSISTENCE_UNIT_NAME);
            EntityTransaction tx = em.getTransaction();
            if (tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                tx.commit();
            }
            EntityManagerContanier.getInstance().clearCurrentManagers();
            PersistenceConfigure.getInstance().setCurrentPUName(null);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                e.printStackTrace();
            }
            logger.error("doing rollback or commit error",e);
        }
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        try {
            EntityManager em = EntityManagerContanier.getInstance().getCurrentEntityManager(IConstants._PERSISTENCE_UNIT_NAME);
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            PersistenceConfigure.getInstance().setCurrentPUName(IConstants._PERSISTENCE_UNIT_NAME);
            return true;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                e.printStackTrace();
            }
            logger.error("Create EntityManger Transaction Fail",e);
        }
        return false;
    }

}
